package com.cp.yn.activity

import android.graphics.Color
import android.os.Bundle
import android.os.CountDownTimer
import android.text.SpannableStringBuilder
import android.text.Spanned
import android.text.TextPaint
import android.text.method.LinkMovementMethod
import android.text.style.ClickableSpan
import android.view.View
import androidx.activity.viewModels
import androidx.lifecycle.lifecycleScope
import com.cp.yn.R
import com.cp.yn.UserManager
import com.cp.yn.databinding.ActivityLoginBinding
import com.cp.yn.dialog.DialogCaptcha
import com.cp.yn.manager.RouterManager
import com.cp.yn.vm.LoginVM
import com.didi.drouter.annotation.Router
import com.lxj.xpopup.XPopup
import com.common.base.base.BaseActivity
import com.common.base.manager.ConfigManager
import com.common.base.tools.arouter.startRouter
import com.common.base.tools.extend.click
import com.common.base.tools.extend.getResourceMipmap
import com.common.base.tools.extend.loadUrl
import com.common.base.tools.extend.stringRes
import com.common.base.tools.utils.JsonUtils
import com.common.base.tools.utils.TToast
import com.cp.yn.bean.NationalBean
import kotlinx.coroutines.launch

@Router(path = RouterManager.Path.APP_Login)
class LoginActivity : BaseActivity<ActivityLoginBinding>() {
    lateinit var countDownJob: CountDownTimer
    private val loginVM by viewModels<LoginVM>()

    private var nationalBean =
        NationalBean(countryCode = "+86", countryName = "中国", icon = "icon_zh", remark = "中国")

    override fun viewBinding(): ActivityLoginBinding {
        return ActivityLoginBinding.inflate(layoutInflater)
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        initAgreementContent()
        setNationalFlag(nationalBean)
    }


    private fun setNationalFlag(nationalBean: NationalBean) {
        viewBinding.phoneCountryCode.text = nationalBean.countryCode
        viewBinding.phoneNationalFlag.setImageResource(getResourceMipmap(nationalBean.icon))
    }

    override fun initListener() {
        super.initListener()
        viewBinding.apply {
            //协议勾选
            agreementCheckbox.click {
                if (agreementCheckbox.tag == "false") {
                    agreementCheckbox.loadUrl(R.mipmap.ic_checkbox_yes)
                    agreementCheckbox.tag = "true"
                } else {
                    agreementCheckbox.loadUrl(R.mipmap.ic_checkbox_no)
                    agreementCheckbox.tag = "false"
                }
            }
            //获取验证码
            codeGetCode.click {
                loginVM.apiSendSmsUrl(phoneInput.text.toString(), "", "+86", UserManager.channel)
            }
            //国旗
            phoneNationalFlagClick.click {
                startRouter(RouterManager.Path.APP_NationalFlag, callback = { resultCode, data ->
                    val nationalBean =
                        data?.getParcelableExtra<NationalBean>(RouterManager.Key.APP_NationalFlag_Result)
                    nationalBean?.let {
                        setNationalFlag(nationalBean)
                    }
                })
            }
            //登录
            login.click {
                if (agreementCheckbox.tag == "true") {
                    loginVM.login(
                        phoneInput.text.toString(),
                        codeInput.text.toString(),
                        "+86",
                        UserManager.channel
                    )
                } else {
                    XPopup.Builder(baseActivity)
                        .isDestroyOnDismiss(true)
                        .isViewMode(true)
                        .dismissOnBackPressed(false)
                        .asConfirm(
                            stringRes(R.string.login_prompt_title),
                            stringRes(R.string.login_prompt_agreement_content),
                            stringRes(R.string.login_cancel),
                            stringRes(R.string.login_confirm),
                            {
                                agreementCheckbox.loadUrl(R.mipmap.ic_checkbox_yes)
                                agreementCheckbox.tag = "true"
                                loginVM.login(
                                    phoneInput.text.toString(),
                                    codeInput.text.toString(),
                                    "+86",
                                    UserManager.channel
                                )
                            },
                            { },
                            false
                        ).show()
                }

            }

            lifecycleScope.launch {

            }

            lifecycleScope.launchWhenCreated {
                //获取验证码结果
                loginVM.flowSendSms.collect {
                    if(it.isNoNetWork()){

                    }

                    if (it.isSuccess()) {
                        startCountDownJob()
                    } else {
                        XPopup.Builder(mContext)
                            .isDestroyOnDismiss(true)
                            .isViewMode(true)
                            .dismissOnBackPressed(false)
                            .asCustom(
                                DialogCaptcha(
                                    mContext,
                                    it.data?.captchaUrl ?: ""
                                ) { captchaUrl ->
                                    loginVM.apiSendSmsUrl(
                                        phoneInput.text.toString(),
                                        captchaUrl,
                                        "+86",
                                        UserManager.channel
                                    )
                                }
                            ).show()
                    }
                }
            }
            lifecycleScope.launchWhenCreated {
                loginVM.flowLogin.collect {
                    if (it.isSuccess()) {
                        UserManager.setToken(it.data?.token)
                        UserManager.setUserId(it.data?.userId)
                        startRouter(RouterManager.Path.APP_Main)
                        finish()
                    } else {
                        //走失败我们也登录进去吧
                        startRouter(RouterManager.Path.APP_Main)
                        TToast.long(JsonUtils.toJson(it))
                        finish()
                    }
                }
            }
        }
    }

    //定时器
    private fun startCountDownJob() {
        countDownJob = object : CountDownTimer(10 * 1000, 1000) {
            override fun onTick(millisUntilFinished: Long) {
                viewBinding.codeGetCode.text = "( ${Math.round(millisUntilFinished / 1000.0)} )"
            }

            override fun onFinish() {
                viewBinding.codeGetCode.text = stringRes(R.string.login_get_captcha)
                viewBinding.codeGetCode.isClickable = true
            }
        }.start()
        viewBinding.codeGetCode.isClickable = false
    }

    /**
     * 初始化协议内容
     */
    private fun initAgreementContent() {
        //SpannableStringBuilder用法
        val builder = SpannableStringBuilder(viewBinding.agreementText.text.toString())
        //同时设置字体颜色、点击事件
        val clickableSpan1: ClickableSpan = object : ClickableSpan() {
            override fun onClick(widget: View) {
                startRouter(RouterManager.Path.APP_WebView)
            }

            override fun updateDrawState(paint: TextPaint) {
                paint.color = Color.parseColor("#5785C1")
                paint.isUnderlineText = false
            }
        }
        val startLeng = if (ConfigManager.configBean?.local == "En") {
            33
        } else {
            12
        }
        builder.setSpan(
            clickableSpan1,
            startLeng,
            viewBinding.agreementText.text.length,
            Spanned.SPAN_EXCLUSIVE_EXCLUSIVE
        )
        //不设置不生效
        viewBinding.agreementText.movementMethod = LinkMovementMethod.getInstance()
        viewBinding.agreementText.text = builder
        //去掉点击后文字的背景色 (不去掉回有默认背景色)
        viewBinding.agreementText.highlightColor = Color.parseColor("#00000000")
    }

}